package net.projecteuler.prob;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.projecteuler.util.PrimeUtil;

import org.jgrapht.demo.CompleteGraphDemo;
import org.jgrapht.demo.HelloJGraphT;
import org.jgrapht.demo.PerformanceDemo;

public class Problem60 implements Runnable{

	static final private int MAX = 5000;
	List<Integer> primeList = null;
	int[] primeDigitCnt = null;
	boolean[] primeTable = null;
	
	public Problem60(){
		primeList = PrimeUtil.getPrimeList(MAX);
		primeDigitCnt = new int[MAX];
		for(int i = 0; i < primeList.size(); i++){
			int prime = primeList.get(i);
			primeDigitCnt[prime] = getDigitCnt(prime);
		}
		int maxPrime = primeList.get(primeList.size() - 1);
		int maxPrime2 = maxPrime * getDigitCnt(maxPrime) + maxPrime;
		List<Integer> primeList2 = PrimeUtil.getPrimeList(maxPrime2); 
		primeTable = new boolean[maxPrime2];
		for(int i = 0; i < primeList2.size(); i++)
			primeTable[primeList2.get(i)] = true;
	}
	
	@Override
	public void run() {
		System.out.println("GO!");
		int size = primeList.size();
		for(int i = 0; i < size; i++){
			int cnt = 0;
			int pi = primeList.get(i);
			List<Integer[]> clique = new ArrayList<Integer[]>();
			for(int j = 0; j < i; j++){
				int pj = primeList.get(j);
				for(int k = 0; k < j; k++){
					int pk = primeList.get(k);
					
					if(isClique(new int[]{pi, pj, pk})){
//						System.out.println(pi + " : " + pj + " : " + pk);
						clique.add(new Integer[]{pj, pk});
						cnt++;
					}
				}
			}
			
			if(cnt >= 6){
				System.out.println("Check " + pi + "(cnt:" + cnt + ")!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			}
		}
	}
	
	private boolean isClique(int[] primes){
		for(int i = 0; i < primes.length; i++){
			for(int j = 0; j < i; j++){
				int pi = primes[i];
				int pj = primes[j];
				
				int pij = pi * primeDigitCnt[pj] + pj;
				int pji = pj * primeDigitCnt[pi] + pi;
				
				if(!primeTable[pij] || !primeTable[pji])
					return false;
			}
		}
		
		return true;
	}
	
	private int getDigitCnt(int value){
		int cnt = 1;
		while(true){
			value /= 10;
			cnt *= 10;
			if(value == 0)
				break;
		}
		
		return cnt;
	}

}
